<? 

		require("required/dbconnect.php"); 	
		require("required/function.php");
		require("required/header.php");
		
		$msg="";
		
		if(isset($_POST['btnAdd']))
		{
			$bid=$_POST['bid'];
			$pid=$_POST['product'];
			$item=$_POST['stock'];
			$quantity=$_POST['quantity'];
			
			
			$chkItemExist=mysql_query("select count(*) as result from os_bill_items where item_id=$item and bid=$bid")or die(mysql_error());
			
			if(mysql_result($chkItemExist,0,"result")>0)
			{
				$msg="<div class='dw_failed'>Selected item is already exist</div>";
			}
			else
			{
				
				$chkItemQuantity=mysql_query("select * from os_product_inventory where id=$item")or die("check 1 ".mysql_error());
				$i=mysql_fetch_array($chkItemQuantity,MYSQL_ASSOC);
			
			
				if($i["quantity"]<$quantity)
				{
					$msg="<div class='dw_failed'>Sorry, the quantity that you have requested is not available.</div>";
					
				}
				else
				{
					$insert=mysql_query("insert into os_bill_items (bid,pid,item_id,price,quantity,add_datetime)
										 values($bid,$pid,$item,'".$i['unit_price']."','$quantity',now())")or die("check 2 ".mysql_error());
					
					updateInvoice($bid);
					$msg="<div class='dw_success'>Record updated!</div>";			
				}
			
			}			

			
			
			
			
		}
		elseif(isset($_POST['btnDelete']))
		{
			$bid=$_POST['bid'];
			$totalItem=$_POST['total_item'];
			$deleteIds="";

			if(!empty($_POST['itemID']))
			{
				$postCount = count($_POST['itemID']);
				$msg="";
				
				if($postCount==$totalItem)
				{
					$msg="<div class='dw_failed'>Sorry, you are not allow to delete all the items in an order.</div>";
				}
				else
				{	
								
					if($postCount!=0)
					{
						for ( $i=0; $i < $postCount; $i++ ) 
						{
							$deleteIds .= $_POST['itemID'][$i].',';
						}
						
						$deleteIds = rtrim($deleteIds,',');
						//echo 'delete from os_bill_items where id in ('.$deleteIds.')';				
						mysql_query('delete from os_bill_items where id in ('.$deleteIds.')');
						updateInvoice($bid);
						$msg="<div class='dw_success'>Record Deleted</div>";
					}
					
				}
								
				
			}
			
			
			
		}
		elseif(isset($_POST['btnUpdate']))
		{
			$bid=$_POST['bid'];
			$get_item=mysql_query("select * from os_bill_items where bid=$bid")or die("line 11".mysql_error());
			$error=0;
			while($c=mysql_fetch_array($get_item))
			{
				$id=$c['id'];
				$quantity=$_POST['q_'.$id];
				
				if($quantity>0 || $quantity!=0 || is_numeric($quantity))
				{
					$chkItemQuantity=mysql_query("select * from os_product_inventory where id=".$c['item_id'])or die("check 1 ".mysql_error());
					$i=mysql_fetch_array($chkItemQuantity,MYSQL_ASSOC);
								
					if($i["quantity"]<$quantity)
					{
						$msg="<div class='dw_failed'>Sorry, the quantity that you have requested is not available.</div>";
						$error=1;
					}
					
				}
				else
				{
					$msg="<div class='dw_failed'>Invalid entry, please check</div>";
					$error=1;
				}			
				
			}
			
			if($error==0)
			{
				$get_item=mysql_query("select * from os_bill_items where bid=$bid")or die("line 11".mysql_error());
				while($c=mysql_fetch_array($get_item))
				{
					$id=$c['id'];
					$quantity=$_POST['q_'.$id];
					$update="update os_bill_items set quantity='$quantity' where id=$id";
					//echo $update."<br>";	
					mysql_query($update);
					updateInvoice($bid);
				}
				$msg="<div class='dw_success'>Data updated!</div>";
			}
			
		}
		elseif(!empty($_GET['bid']))
		{
			$bid=$_GET['bid'];
		}
		else
		{
			die("Invalid access");
		}	
			
		$get_item=mysql_query("select * from os_bill_items where bid=$bid")or die("line 11".mysql_error());
		
	
?>

<script language="JavaScript" type="text/javascript" src="required/js/goAjax.js"></script>

<script language="javascript">
	function getSubCat(id)
	{ 
		
		changeContent("required/js/getsubcat.php?showprod=1&catid="+id,"divSubcat");	
	}
	
	function getProduct(id)
	{ 
		changeContent("required/js/getproduct.php?subcatid="+id,"divProduct");	
	}
	
	function getStock(id)
	{ 
		changeContent("required/js/getstock.php?prodid="+id,"divStock");	
	}
	
	function validateFrm(frm1)
	{
		if(document.frm1.cat_id.value=="")
		{
			alert("Please select main category");
			return false;
		}
		
		if(document.frm1.sub_cat.value=="")
		{
			alert("Please select sub category");
			return false;
		}
		
		if(document.frm1.product.value=="")
		{
			alert("Please select product");
			return false;
		}
		
		if(document.frm1.stock.value=="")
		{
			alert("Please select stock");
			return false;
		}
		
		if(document.frm1.quantity.value=="")
		{
			alert("Please enter quantity");
			return false;
		}
		
		if(document.frm1.quantity.value=="0")
		{
			alert("Quantity cannot be zero");
			return false;
		}
		
		if(!isInteger(document.frm1.quantity.value))
	 	{
			alert("Please enter integer only");
			return false;
	   	}
		
		return true;
	}
	

   function isInteger (s)
   {
	  var i;

	  if (isEmpty(s))
	  if (isInteger.arguments.length == 1) return 0;
	  else return (isInteger.arguments[1] == true);

	  for (i = 0; i < s.length; i++)
	  {
		 var c = s.charAt(i);

		 if (!isDigit(c)) return false;
	  }

	  return true;
   }

</script>
<table width="100%" cellpadding="5">
	
		<Td valign="top">
        	<?= $msg ?>
				<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
				<table width="95%" bgcolor="#CCCCCC" cellpadding="5" cellspacing="1">
                    <tr bgcolor="#F3F3F3" align="center">
                        <Td></Td><td width="42%">Product</td><td width="13%">Price(RM)</td><td width="15%">Product code</td>
                        <td width="11%">Quantity</td><td width="15%">Total(RM)</td>
                    </tr>
			<?
					$total_item=0;
					$total_piece=0;
					$total_allprice=0;
					while($c=mysql_fetch_array($get_item))
					{
						$total_price=0;
						$get_product=mysql_query("select a.product_name_eng,a.product_code,b.description,b.unit_price from os_products a 
						inner join os_product_inventory b on a.id=b.pid where b.id=".$c['item_id']);
						$a=mysql_fetch_array($get_product,MYSQL_ASSOC);
						$total_price=$a['unit_price']*$c['quantity'];
						$total_allprice=$total_allprice+$total_price;
						$total_item++;
																
			?>
                    <tr bgcolor="#FFFFFF" align="center">
                        <td><input type="checkbox" name="itemID[]" value="<?= $c['id']?>" /></td>
                        <td align="left"><a href="product_viewfull.php?id=<?= $c['pid'] ?>"><?= $a['product_name_eng'] ?></a>
                        <br>Product Option : <strong><?= $a['description'] ?></strong></td>
                        <td><?= $a['unit_price'] ?></td><td><?= $a['product_code'] ?></td>
                        <td><input type="text" value="<?= $c['quantity'] ?>" class="text" name="q_<?= $c['id'] ?>" size="2" maxlength="3" /></td>
                        <td align="right"><?= number_format($total_price,2) ?></td>
                    </tr>
			<? 
				
					} 
			?>
           
				</table>
			<br><br>
			
                <input type="submit" value="Update" class="button" name="btnUpdate" />
                
                <input type="submit" value="Delete Selected" class="button" name="btnDelete" onclick="return confirm('Confirm to delete?')" />
                
                <input type="button" value="Back" class="button" onclick="window.open('order_viewfull.php?id=<?= $bid ?>','_self')" />
                
                <input type="hidden" value="<?= $bid ?>" name="bid" />
                <input type="hidden" value="<?= $total_item ?>" name="total_item" />
            </form>
            
            <form action="<?= $_SERVER['PHP_SELF'] ?>" name="frm1" method="post" onsubmit="return validateFrm(this)">
            <table width="100%">
	            <td class="title" colspan="2"><strong>Add Product</strong></td>
            
				<?
                    $get_cat=mysql_query("select * from os_category order by id asc");
                
                ?>
	            <tr>
                    <Td width="13%">Main Category</Td>
                    <td width="87%">
                        <select name="cat_id" class="text" onChange="getSubCat(this.value)">
                            <option value="" selected="selected">Please Select</option>
                        <?
                            while($c=mysql_fetch_array($get_cat,MYSQL_ASSOC))
                            {
                        ?>
                            <option value="<?= $c['id'] ?>"><?= $c['name_eng'] ?></option>
                        <? } ?>
                        </select>
                    
                	</td>
           		 </tr>
                <tr>
                    <td>Sub Category</td><td>
                    <div id="divSubcat">
                        <select name="sub_cat" class="text">
                            <option value="">Please select main category</option>
                        </select>						
                    </div>
                    </td>
                    
                </tr>
                <tr>
                	<td>Product</td><td>
                    <div id="divProduct">
                        <select name="product" class="text">
                            <option value="">Please select sub category</option>
                        </select>						
                    </div>
                    </td>
                </tr>
                <tr>
                	<td>Available Stock</td><td>
                    <div id="divStock">
                        <select name="stock" class="text">
                            <option value="">Please select product</option>
                        </select>						
                    </div>
                    </td>
                </tr>
                 <tr>
                	<td>Quantity</td><td>
                    
                        <input type="text" value="0" name="quantity" class="text" size="3" maxlength="4" />
                    
                    </td>
                </tr>
                <tr>
                	<td>
                    	<input type="hidden" value="<?= $bid ?>" name="bid" />
                    	<input type="submit" value="Add" class="button" name="btnAdd" />
                    </td>
                </tr>
                
            </table>
            </form>
            </td>
           </table>
			
<? require("required/footer.php"); ?>	